/**
 * create by Alec
 */

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";

// submodule
import Profile from "./profile";
import "./index.less";

// utils
import { get } from "../../utils/db.js";

// actions
import { fetchConfirm, fetchAllDropDown } from "../../actions/confirm/index.js";

//将store注入组件的props
const mapStateToProps = state => ({
  user: { ...state.CONFIRM_USER },
  options: { ...state.CONFIRM_OPTION }
});
//将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
  //区分绑定到props的action与传递的props
  actions: bindActionCreators(
    {
      dispatch,
      fetchConfirm,
      fetchAllDropDown
    },
    dispatch
  )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Confirm extends Component {
  static defaultProps = {
    user: {},
    options: {}
  };
  //propTypes 验证
  static propTypes = {
    actions: PropTypes.shape({
      dispatch: PropTypes.func.isRequired,
      fetchConfirm: PropTypes.func.isRequired,
      fetchAllDropDown: PropTypes.func.isRequired
    }).isRequired
  };
  constructor(props) {
    super(props);
    this.state = { user: {}, options: {} };
  }
  componentWillMount() {
    const userId = get("userId");
    this.props.actions.fetchConfirm(userId).then(res => {
      if (res.success) {
        const user = res.result;
        const deptMapList =
          user.deptMapList.sort((a, b) => a.deptId - b.deptId) || [];
        this.setState({
          deptsId: deptMapList.map(val => val.deptId),
          deptsName: deptMapList.map(val => val.deptName),
          user,
          employeeType: res.result.employeeType
        });
      }
    });
    this.props.actions.fetchAllDropDown().then(res => {
      if (res.success) {
        this.setState({ options: res.result });
      }
    });
  }

  render() {
    const { user, options, deptsId, deptsName, employeeType } = this.state;
    return (
      <div className="confirm-wrap">
        <Profile
          user={user}
          options={options}
          deptsId={deptsId}
          deptsName={deptsName}
          employeeType={employeeType}
        />
      </div>
    );
  }
}
